<?php
/**
 * Created by PhpStorm.
 * User: hongtianjin
 * Date: 2017/3/2 0002
 * Time: 18:23
 */

namespace App\Http\Controllers\Web\ActivityDelivery;

use App\App\Services\Web\UserService;
use App\Http\Controllers\Controller;
use App\Models\ActivityDelivery\ActivityDelivery;
use App\Models\ActivityDelivery\ActivityDeliveryService;
use App\Models\ActivityPoints\ActivityPointsService;
use App\Models\User\User;
use Illuminate\Http\Request;

class ActivityDeliveryController extends Controller
{
    public function index(Request $request, ActivityDeliveryService $activityDeliveryService, ActivityPointsService $activityPointsService)
    {
        //$res = $activityDeliveryService->getAvailablePoints();

        return view('web.activityDelivery.list');
    }

    /**
     * 活动投放列表
     */
    public function activityDeliveryList(Request $request, ActivityDeliveryService $activityDeliveryService, UserService $userService)
    {
        $loginUser = $userService->getLoginUser();
        $user_id = $loginUser['id'];
        $res = $activityDeliveryService->getActivityDeliveryListByPage($request, $user_id);

        return $this->respondJson($res);
    }

    /**
     * 修改投放状态
     *
     * @param Request                 $request
     * @param ActivityDeliveryService $activityDeliveryService
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request, ActivityDeliveryService $activityDeliveryService)
    {
        $id = $request->input('id');
        if ($request->isMethod('post')) {
            $input = $request->request->all();
            $update = [];
            if (!is_null($input['status'])) {
                $update['status'] = $input['status'];
            }
            $res = $activityDeliveryService->saveActivityDeliveryById($update, $id);

            return $this->respondJson([
                'message' => '保存成功',
            ]);
        }

        return $this->respondJson([
            'message' => '保存失败',
        ]);
    }

    public function showDeliveries(ActivityDeliveryService $activityDeliveryService)
    {
        $data = $activityDeliveryService->getAvailablePoints();

        return view('web.activityDelivery.add', ['data' => $data]);
    }

    public function editActivityDelivery(Request $request, ActivityDeliveryService $activityDeliveryService, ActivityPointsService $activityPointsService)
    {
        $id = $request->input('id');
        $deliveryData = $activityDeliveryService->getActivityDeliveryAndDetailsById($id);
        $pointData = $activityDeliveryService->getAvailablePoints($deliveryData[0]['point_id']);

        return view('web.activityDelivery.edit', ['deliveryData' => $deliveryData[0], 'pointData' => $pointData]);
    }

    /**
     * 新建投放
     *
     * @param Request                       $request
     * @param ActivityDeliveryService       $activityDeliveryService
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request, ActivityDeliveryService $activityDeliveryService, UserService $userService)
    {
        $this->_validateActivityDeliveryParams($request);//验证参数是否合法

        $activityDeliveryDetailData = $request->input('detail');
        $this->_validateDetail($activityDeliveryDetailData);

        $activityDeliveryData = $this->_getActivityDeliveryDataFormat($request, $userService);//格式化数据
        //array_set($activityDeliveryData, 'img_url', 'tmp.png');

        $res = $activityDeliveryService->createDeliveryAndDetail($activityDeliveryData);

        if ($res) {
            return $this->respondJson(['message' => '新建投放成功','code'=>0]);
        } else {
            return $this->respondJson(['message' => '新建投放失败', 'code' => 1]);
        }
    }

    /**
     * 格式化数据
     * @param Request $request  请求参数
     * @param UserService $userService 用户服务
     * @return mixed
     */
    public function _getActivityDeliveryDataFormat(Request $request, UserService $userService)
    {
        $activityDeliveryDetailData = $request->input('detail');
        $platformArray = $request->input('platform');
        $platform = 0;
        foreach ($platformArray as $key=>$val) {
            $platform = $platform | $val;   //转成二进制储存
        }
        $activityDeliveryData['point_id'] = $request->input('point_id');
        $activityDeliveryData['name'] = $request->input('name');
        $activityDeliveryData['platform'] = $platform;
        $activityDeliveryData['type'] = $request->input('type');
        if ($userService instanceof UserService) {
            $loginUser = $userService->getLoginUser();
            $activityDeliveryData['user_id'] = $loginUser['id'];
        }
        $detail = $activityDeliveryDetailData[0];
        $act_type = $detail['act_type'];
        $activityDeliveryData['act_id'] = ($act_type == ActivityDelivery::ACTIVITY_DELIVERY_ACT_TYPE_LIST) ? $detail['act_id'] : 0;
        $activityDeliveryData['act_name'] = $detail['act_name'];
        $activityDeliveryData['img_url'] = $detail['img_url'];
        $activityDeliveryData['begin_time'] = strtotime($detail['begin_time']);
        $activityDeliveryData['end_time'] = strtotime($detail['end_time']);
        $activityDeliveryData['act_type'] = $act_type;
        $activityDeliveryData['target'] = $detail['target'];

        return $activityDeliveryData;
    }

    /**
     * 验证参数是否合法
     * @param Request $request
     * @return bool|\Illuminate\Http\JsonResponse
     */
    public function _validateActivityDeliveryParams(Request $request, $action = 'add')
    {
        if ($action == 'edit') {
            $this->validate($request, [
                'id' => 'required',
            ], [
                'id.required' => '参数ID不能为空',
            ]);
        }

        $this->validate($request, [
            'point_id' => 'required',
            'name' => 'required',
            'platform' => 'required',
            'type' => 'required',
        ], [
            'point_id.required' => '请选择埋点',
            'name.required' => '请添加活动名称',
            'platform.required' => '请选择平台',
            'type.required' => '请选择投放类型',
        ]);

        return true;
    }
    public function _validateDetail($activityDeliveryDetailData)
    {
        if (is_array($activityDeliveryDetailData)) {
            foreach ($activityDeliveryDetailData as $key => $data) {
                $begin_time = strtotime($data['begin_time']);
                $end_time = strtotime($data['end_time']);
                if ($begin_time >= $end_time) {
                    return $this->respondJson(['message' => '活动时间填写有误', 'code' => 1]);
                }
                if ($data['act_name'] == '') {
                    return $this->respondJson(['message' => '请添加投放活动', 'code' => 1]);
                }
                if ($data['img_url'] == '') {
                    return $this->respondJson(['message' => '请添加背景图片', 'code' => 1]);
                }
                if ($data['act_type'] == ActivityDelivery::ACTIVITY_DELIVERY_ACT_TYPE_SELF) {
                    $rule = '/^((https|http)?:\/\/)[^\s]+/';
                    if (!preg_match($rule, $data['act_name'])) {
                        return $this->respondJson(['message' => '自有活动格式错误', 'code' => 1]);
                    }
                }
            }
        }
        return true;
    }
    /**
     * 编辑投放
     *
     * @param Request                       $request
     * @param ActivityDeliveryService       $activityDeliveryService
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function modify(Request $request, ActivityDeliveryService $activityDeliveryService, UserService $userService)
    {
        $this->_validateActivityDeliveryParams($request, "edit");
        $activityDeliveryDetailData = $request->input('detail');
        $this->_validateDetail($activityDeliveryDetailData);

        $activityDeliveryData = $this->_getActivityDeliveryDataFormat($request, $userService);

        $id = $request->input('id');
        $res = $activityDeliveryService->modifyDeliveryAndDetail($activityDeliveryData, $id);
        if ($res) {
            return $this->respondJson(['message' => '修改成功']);
        } else {
            return $this->respondJson(['message' => '修改失败', 'code' => 1]);
        }
    }

    /**
     * 删除投放
     * @param Request $request
     * @param ActivityDeliveryService $activityDeliveryService
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request, ActivityDeliveryService $activityDeliveryService)
    {
        $ids = $request->input('ids');
        $this->validate($request, [
            'ids' => 'required',
        ], [
            'ids.required' => '投放ID不能为空',
        ]);
        $res = $activityDeliveryService->deleteActivityDeliveries($ids);

        return $this->respondJson([
            'message' => '删除成功',
        ]);
    }
}
